import TextWidget from './text-widget.js'
import {WIDGET_TYPE} from './widget-const.js';
//import {ToastMessager, MessagerLevel} from '../messager.js'

const _DefaultCodeHandler = () => {};

export default class ScriptWidget extends TextWidget {
    constructor(sectionData, dispatcher) {
        super(sectionData, dispatcher);
        this._codeHandler = _DefaultCodeHandler;
    }
    get sectionData() {
        this._sectionData.type = WIDGET_TYPE.SCRIPT;
        return this._sectionData;
    }
    get language() {return 'javascript';}
    Init() {
        super.Init();
        this._editContainerElem.setAttribute('data-language', 'script');
        return this;
    }
    Deinit() {
        this._ExecuteCustomCode();
        super.Deinit();
    }
    _ExecuteCustomCode() {
        try {
            if (this._codeHandler) {
                this._codeHandler();
            }
            this._codeHandler = undefined;
        } catch (e) {
            this._codeHandler = undefined;
            console.error(e.message);
            console.error(e.stack);
        }
    }
    _UpdateView() {
        this._ExecuteCustomCode();
        try {
            //this._viewContainerElem.innerHTML = `<div class='slog-script-notation' style="color:darkgrey">script code</div>`;
            const _tmpFn = new Function('_elem', this.textareaText);
            this._codeHandler = _tmpFn(this._viewContainerElem);
            if (this._codeHandler) {
                if (this._codeHandler instanceof Function) {
                    return;
                }
            }
            this._codeHandler = _DefaultCodeHandler;
        } catch (e) {
            this._codeHandler = _DefaultCodeHandler;
            this._viewContainerElem.innerHTML = `<div class='slog-script-notation' style="color:darkgrey">error with your input. more info please checkout console.</div>`;
            //ToastMessager.Show(`error with your input. more info please checkout console.`, MessagerLevel.ERROR);
            this._viewContainerElem.innerText = e.message;
            console.error(e.stack);
        }
        return true;
    }
};

